<!-- 弹窗 详情 -->
<script lang="tsx" setup>
import FileUpload from "@/components/file-system/file-upload.vue";
import type { FormDescChild } from "@/components/form-desc/form-desc.vue";
import {
	jeecgBootExQuebankPageUsingPost,
	jeecgBootExExamSaveUsingPost,
	jeecgBootExExamUpdateUsingPut,
} from "@/genapi/exam";
import { useAsync } from "@/hooks/use-async";
import FileOtherUpload from "@/components/file-system/file-otherUpload.vue";
import { ref } from "vue";
import {
	getEnumOptionsField,
	COURSE_TYPE_OPTIONS,
	RECORD_TYPE_OPTIONS,
} from "@/config/enum-options";

import { injectState } from "../state";

defineOptions({ name: "DetailDialog" });

const img = import.meta.glob("./assets/*.png", {
	import: "default",
	eager: true,
});

const { page } = injectState()!;

const dialogRef = shallowRef<InstanceType<GlobalComponents["PromiseDialog"]>>();
const formDescRef = shallowRef<InstanceType<GlobalComponents["FormDesc"]>>();

const type = ref<"download" | "write" | "read">();

const beforeClose = async () => {
	if (type.value === "write") {
		await ElMessageBox.confirm("确认关闭？");
	}
};

const trigger = async (
	_type: "download" | "write" | "read",
	value = {} as any,
) => {
	type.value = _type;
	model.value = JSON.parse(JSON.stringify(value)) as any;
	tableData.value = [];
	datetimeRange.value = [model.value.startDate, model.value.endDate];
	await dialogRef.value?.open();
};

defineExpose({
	trigger,
});

const model = ref<(typeof page.records.value)[0]>({});
const value = ref("");

const file = computed({
	get() {
		if (model.value.fileId) {
			return [
				{
					id: model.value.fileId,
					name: model.value.fileName,
				},
			];
		}
	},
	set(value: any) {
		model.value.fileId = value?.[0]?.id;
	},
});

const title = computed(() => {
	if (type.value === "write") {
		return model.value.id ? "编辑" : "新建";
	} else {
		return `详情`;
	}
});

const { execute, isLoading } = useAsync(async () => {
	await formDescRef.value?.formRef?.validate();
	await ElMessageBox.confirm("确认提交？", "提示", {
		type: "warning",
	});
	// debugger;
	model.value.startDate = datetimeRange.value[0];
	model.value.endDate = datetimeRange.value[1];
	model.value.queBankList = tableData.value;
	if (type.value === "create") {
		await jeecgBootExExamSaveUsingPost({
			data: {
				...model.value,
			},
		});
	} else if (type.value === "write") {
		await jeecgBootExExamUpdateUsingPut({
			data: {
				...model.value,
			},
		});
	}

	ElMessage.success("提交成功");
	page.execute();
	dialogRef.value?.complete();
});
const selectOptions = ref([{ label: "员工", value: "1" }]);

const datetimeRange = ref();

const children: FormDescChild[] = [
	{
		label: "考试名称",
		prop: "name",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.name} placeholder="请输入" />
		),
		descItem: () => `${model.value.name ?? "-"}`,
	},
	{
		label: "考试类型",
		prop: "category",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-select-v2
				v-model={model.value.category}
				options={COURSE_TYPE_OPTIONS}
				clearable
				placeholder="请选择类型"
			/>
		),
		descItem: () =>
			getEnumOptionsField(COURSE_TYPE_OPTIONS, "label", model.value.status) ??
			"-",
	},
	{
		label: "总分数",
		prop: "totalScore",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input
				disabled
				v-model={model.value.totalScore}
				placeholder="请输入"
			/>
		),
		descItem: () => `${model.value.totalScore ?? "-"}`,
	},
	{
		label: "及格分",
		prop: "passScore",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.passScore} placeholder="请输入" />
		),
		descItem: () => `${model.value.passScore ?? "-"}`,
	},
	{
		label: "考试时长（分钟）",
		prop: "duration",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.duration} placeholder="请输入" />
		),
		descItem: () => `${model.value.duration ?? "-"}`,
	},
	{
		label: "考试期限",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-date-picker
				v-model={datetimeRange.value}
				clearable
				type="datetimerange"
				placeholder="考试期限"
			/>
		),
		descItem: () =>
			`${model.value.startDate ?? "-"}-${model.value.endDate ?? "-"}`,
	},
];

const tableData = ref([
	{
		queBankId: "",
		scCount: 0,
		scScore: 0,
		mcCount: 0,
		mcScore: 0,
		yonCount: 0,
		yonScore: 0,
	},
]);

/** 鼠标移入cell */
const handleCellEnter = (row, column, cell, event) => {
	row.isEdit = true;
};

/** 鼠标移出cell */
const handleCellLeave = (row, column, cell, event) => {
	row.isEdit = false;
};

const sumScore = computed(() => {
	let sum = 0;
	tableData.value.forEach((item) => {
		sum +=
			item.scScore * item.scCount +
			item.mcScore * item.mcCount +
			item.yonScore * item.yonCount;
	});
	model.value.totalScore = sum;
	return sum;
});

const addRow = () => {
	tableData.value.push({
		queBankId: "",
		scCount: 0,
		scScore: 0,
		mcCount: 0,
		mcScore: 0,
		yonCount: 0,
		yonScore: 0,
	});
};

const removeRow = (scope) => {
	tableData.value.splice(scope.$index, 1);
};

const options = ref([]);

const getOptions = async () => {
	const res = await jeecgBootExQuebankPageUsingPost({
		data: {
			size: 999,
			current: 1,
		},
	});
	res.result?.records?.map((item) => {
		options.value.push({
			label: item.name,
			value: item.id,
		});
	});
};

onMounted(() => {
	getOptions();
});
</script>

<template>
	<PromiseDialog
		ref="dialogRef"
		:title="title"
		:before-close="beforeClose"
		w="1200px!"
	>
		<el-scrollbar style="height: 508px">
			<div>
				<div
					style="
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 100%;
						height: 40px;
					"
				>
					<el-button size="small" type="primary" @click="addRow"
						>添加</el-button
					>
					<span>试卷总分：{{ sumScore }}分</span>
				</div>
				<el-table
					:data="tableData"
					size="small"
					style="width: 100%"
					@cell-mouse-enter="handleCellEnter"
					@cell-mouse-leave="handleCellLeave"
					show-overflow-tooltip
				>
					<el-table-column prop="name" label="题库名称">
						<template #default="scope">
							<el-select
								v-model="scope.row.queBankId"
								placeholder="请选择题库"
								size="small"
								style="width: 240px"
							>
								<el-option
									v-for="item in options"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</el-select>
						</template>
					</el-table-column>
					<el-table-column prop="scCount" label="单选数量" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.scCount"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.scCount }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="scScore" label="单选分数" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.scScore"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.scScore }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="mcCount" label="多选数量" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.mcCount"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.mcCount }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="mcScore" label="多选分数" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.mcScore"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.mcScore }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="yonCount" label="判断题数量" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.yonCount"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.yonCount }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="yonScore" label="判断题分数" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.yonScore"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.yonScore }}</div>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="80" v-if="tableData.length > 1">
						<template #default="scope">
							<el-button type="text" @click="removeRow(scope)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<FormDesc
				ref="formDescRef"
				m="t-24px x-30px"
				:type="type === 'read' ? 'desc' : 'form'"
				form-class="gap-x-20px"
				:model="model"
				:children="children"
				:column="2"
			/>
		</el-scrollbar>
		<template v-if="type === 'write' || type === 'create'" #footer>
			<el-button @click="dialogRef?.close()">取消</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>确定</el-button
			>
		</template>
		<template v-else-if="type === 'read'" #footer>
			<el-button @click="dialogRef?.close()">拒绝</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>通过</el-button
			>
		</template>
	</PromiseDialog>
</template>

<style lang="scss" scoped>
.trainingListBox {
	width: 100%;
	padding: 0px 30px;

	.listBoxTitle {
		height: 50px;
		width: 100%;
		display: flex;
		align-items: center;
	}
}
.item {
	width: 100px;
	/* 调整elementUI中样式 如果不需要调整请忽略 */
	.el-input__inner {
		height: 24px !important;
	}
}
.txt {
	line-height: 24px;
	padding: 0 9px;
	box-sizing: border-box;
}
</style>
